package com.crazybird.vote.config;

import com.crazybird.vote.entity.VoteConstant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.data.redis.core.RedisKeyValueTemplate;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.support.atomic.RedisAtomicInteger;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author JG.Hannibal
 * @since 2017/12/12 下午10:45
 */
@Component
public class StartupListenerConfig implements ApplicationListener<ContextRefreshedEvent> {

    public static final Logger logger = LoggerFactory.getLogger(StartupListenerConfig.class);
    @Resource
    private RedisTemplate<String,Integer> redisTemplate;
    public static List<Integer> ids =new ArrayList<Integer>(){{add(1);add(2);add(20);add(21);add(22);add(23);add(24);add(25);add(26);add(27);}};
    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        // todo something after App initialized.
        logger.info("启动成功");
        List<String> keys = ids.stream().map(String::valueOf)
                .map(o->{return  VoteConstant.VOTE_TICKET +o;}).collect(Collectors.toList());
        List<Integer> integers = redisTemplate.opsForValue().multiGet(keys);
        if (keys.size() != integers.size()){
            logger.warn("有key没返回值");
            return;
        }
        for (int i = 0 ;i <keys.size();i++){
            if (integers.get(i) == null){
                redisTemplate.opsForValue().set(keys.get(i),0);
            }
        }
    }
}
    